<?php

namespace app\index\controller;

use think\Controller;
use app\index\model\User;
use think\Db;

use app\index\controller\Basecontroller;


class Index extends Basecontroller
{
  function index()
  {
    return '欢迎来到tp5';
  }
  /**
   * 获得轮播图数据
   */
  function getBanner()
  {
    $res = db('goods')
      ->field('gid , g_picture ,g_longImg ,g_name')
      ->where(['g_state' => 0])
      ->limit(0, 20)
      ->select();
    return res(1000, 'ok', $res);
  }

  /**
   * 获得最热商品数据
   */
  function getHotRecommend()
  {
    $res = db('goods')
      ->field('gid , g_picture ,g_name ,g_start_money')
      ->where(['g_state' => 0])
      ->limit(0, 4)
      ->order('buy_num desc')
      ->select();
    return res(1000, 'ok', $res);
  }

  /**
   * 获得最新商品数据
   */
  function getNewGoods()
  {
    $res = db('goods')
      ->field('gid , g_picture ,g_name ,g_start_money ,g_end_money')
      ->limit(0, 4)
      ->where(['g_state' => 0])
      ->order('g_create_time desc')
      ->select();
    $res2 = db('goods')
      ->field('gid , g_picture ,g_name ,g_start_money ,g_end_money')
      ->limit(0, 4)
      ->where(['g_state' => 0])
      ->order('g_create_time asc')
      ->select();
    return res(1000, 'ok', [$res, $res2]);
  }
  /**
   * 获得分类商品数据
   */
  function getCategory()
  {
    $res = db('classify')
      ->field('cid , c_name')
      ->where('fid != 0')
      ->select();

    // $classArr = [];
    foreach ($res as $key => &$value) {

      $item = db('goods')
        ->where("cid = {$value['cid']}")
        ->field('gid , g_picture ,g_name ,g_start_money ,g_end_money')
        ->where(['g_state' => 0])
        ->limit(0, 8)
        ->select();
      $value['children'] = $item;
    }
    return res(1000, 'ok', $res);
  }
  /**
   * 用户注册
   * 请求方式：post
   * 参数：
   * acc：Sting
   * pwd：Sting
   * nickname：Sting
   */

  function register()
  {

    $data = getPost();
    // 进行名称查重
    $nickname = [
      'nickname' => $data['nickname'],
    ];
    $res = db('user')->where($nickname)->find();
    if ($res) {
      return res(1001, '用户名已存在');
    }
    $acc = [
      'acc' => $data['acc'],
    ];
    $res = db('user')->where($acc)->find();
    if ($res) {
      return res(1002, '账号已存在');
    }

    $insert = [
      'acc' => $data['acc'],
      'pwd' => myMd5($data['pwd']),
      'nickname' => $data['nickname'],
      'create_time' => date('Y-m-d H:i:s'),
    ];

    $res = db('user')->insert($insert);
    if ($res) {
      return res(1000, 'ok');
    }
    return res(1050, '服务器繁忙，请稍后重试');
  }
  /**
   * 用户登录
   * 请求方式：post
   * 参数
   * acc:string
   * pwd:string
   */
  function userLogin()
  {
    $data = getPost();
    // 密码进行加密
    $data['pwd'] = myMd5($data['pwd']);

    $res =  db('user')->where($data)->find();
    if (!$res) {
      return res(1001, '账号密码错误');
    }

    // 删除储存中的token
    $this->redis->del($res['token']);
    // 生成新的token
    $token = create_token();
    // 将新的token存入数据库中
    db('user')->where('uid', $res['uid'])->update([
      'token' => $token
    ]);

    $this->redis->set($token, json_encode($res), $this->time);

    return res(1000, 'ok', $token);
  }

  /**
   * 获取当前登录的用户
   * 请求方式：get
   * 参数
   * head内携带token
   */
  function getLoginUser()
  {
    // $token = getheaders()['Access-Token'];
    // // 获得token
    // // 判断token值是否正确
    // if (!$token) {
    //   return res('1001', 'token 无效');
    // }
    // $res = $this->redis->get($token);
    // if (!$res) {
    //   return res('1001', 'token 无效');
    // }
    // $res = json_decode($res, true);

    $res = $this->verifyLogin_user();
    if (!$res) {
      return res('1001', 'token 无效');
    }
    $userData = [
      'nickname' => $res['nickname'],
      'head' => $res['head'],
      'money' => $res['money'],
      'desc' =>  $res['desc'],
      'create_time ' => $res['create_time'],
      'address' => $res['address'],
      'uid' => $res['uid'],

    ];


    return res(1000, 'ok', $userData);
  }
  /**
   * 用户退出登录
   * 删除token
   */
  function userLogout()
  {
    $token = getheaders()['Access-Token'];
    $this->redis->del($token);
    return res(1000, 'ok');
  }

  /**
   *用户上传头像
   */
  function headUpload()
  {
    $token = getheaders()['Access-Token'];
    $file = request()->file('image');
    // $file->rule('uniqid')->move('/home/www/upload/');
    $tokenData = json_decode($this->redis->get($token), true);

    // 移动到框架应用根目录/public/uploads/ 目录下
    if ($file) {
      $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
      if ($info) {
        // 成功上传后 获取上传信息
        // 输出 jpg
        // echo $info->getExtension();
        // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
        // echo $info->getSaveName();
        // 输出 42a79759f284b767dfcb2a0197904287.jpg
        // echo $info->getFilename();
        $imgPath = str_replace('\\', "/", $info->getSaveName());;


        $path = $this->file_path . $imgPath;

        $res = db('user')->where([
          'uid' => $tokenData['uid']
        ])->update(
          ['head' => $path]
        );

        if ($res === 1) {
          return res(1000, 'ok' );
        }
      } else {
        // 上传失败获取错误信息
        echo $file->getError();
      }
    }
  }
  // 聊天图片上传
  function chatImgLoad()
  {
    $file = request()->file('image');

    if ($file) {
      $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
      if ($info) {
        // 成功上传后 获取上传信息
        // 输出 jpg
        // echo $info->getExtension();
        // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
        // echo $info->getSaveName();
        // 输出 42a79759f284b767dfcb2a0197904287.jpg
        // echo $info->getFilename();
        $imgPath = str_replace('\\', "/", $info->getSaveName());;


        $path = $this->file_path . $imgPath;
        return  res(1000,'ok',$path );
        
      } else {
        // 上传失败获取错误信息
        echo $file->getError();


      }
    }

  }

  /**
   * 用户修改信息
   */
  function editUserInfo()
  {
    $data = getPost();
    $token = getheaders()['Access-Token'];
    $tokenData = json_decode($this->redis->get($token), true);
    if (!$token || !$tokenData) {
      return res(1001, '服务器繁忙，请稍后再试');
    }
    $where = "uid != '{$tokenData['uid']}' and nickname = '{$data['nickname']}' ";

    // 查询昵称是否存在重复
    $res = db('user')->where($where)->find();
    if ($res) {
      return  res(1002, '昵称已经存在了！');
    }
    $res = db('user')->where([
      'uid' => $tokenData['uid']
    ])->update(
      $data
    );
    if ($res === 1) {
      return res(1000, 'ok');
    }
    return res(1001, '服务器繁忙，请稍后再试');
  }




  // function insert(){
  //   $res = db('goods')
  //   ->field('gid , g_name' )
  //   ->select();
  //   foreach ($res as $key => &$value) {
  //     for ($i=1; $i < 4 ; $i++) { 
  //       $item = [
  //         'gid'=>$value['gid'],
  //         'name'=>$value['g_name']."的第{$i}个子项目",
  //         'desc'=>$value['g_name']."第{$i}个子项目的描述",
  //         'price'=>mt_rand(50,10000),
  //         'buyer'=>mt_rand(20,200),
  //         'limit_num'=>200,
  //         'store_num'=>1000,
  //       ];

  //       db('goodsitem')->insert($item);
  //     }

  //   }

  //   return res(1000,'ok',$res);

  // }
}
